﻿using Microsoft.Cci;
using System;

namespace AutoPex.Core
{
	internal sealed class HostEnvironment : MetadataReaderHost
	{
		PeReader peReader;

		internal HostEnvironment()
			: base()
		{
			this.peReader = new PeReader(this);
		}

		public override IUnit LoadUnitFrom(string location)
		{
			var result = this.peReader.OpenModule(
			  BinaryDocument.GetBinaryDocumentForFile(location, this));
			this.RegisterAsLatest(result);
			return result;
		}

		public override IBinaryDocumentMemoryBlock OpenBinaryDocument(
			IBinaryDocument parentSourceDocument, string childDocumentName)
		{
			return UnmanagedBinaryMemoryBlock.CreateUnmanagedBinaryMemoryBlock(
				childDocumentName, parentSourceDocument);
		}

		public override IBinaryDocumentMemoryBlock OpenBinaryDocument(
			IBinaryDocument sourceDocument)
		{
			if(sourceDocument == null)
			{
				throw new ArgumentNullException("sourceDocument");
			}

			return UnmanagedBinaryMemoryBlock.CreateUnmanagedBinaryMemoryBlock(
				sourceDocument.Location, sourceDocument);
		}
	}
}
